package com.edu.controller.user;

import com.edu.entity.User;
import com.edu.service.user.UserService;
import com.edu.service.user.UserServiceImpl;
import com.edu.utils.ParamFormat;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @author ZCN
 * @version 1.0
 * @date 2021/11/18 14:18
 */
@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 格式化参数
            ParamFormat.format(req, resp);
            Map<String, String[]> map = req.getParameterMap();
            User user = new User();
            BeanUtils.populate(user,map);
            int loginflag = userService.login(user);
            if(loginflag == -1){
                // 表示用户名或密码错误
                req.setAttribute("error","用户名或密码错误");
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }else if(loginflag == 0){
                // 表示普通用户
                HttpSession session = req.getSession();
                session.setAttribute("username",user.getUsername());
                resp.sendRedirect("/front/index");
            }else if(loginflag == 1){
                // 表示管理员用户
                HttpSession session = req.getSession();
                session.setAttribute("username",user.getUsername());
                resp.sendRedirect("/system/sysindex.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
